package week07.necessary.batchinsert;

import lombok.extern.slf4j.Slf4j;
import week07.necessary.batchinsert.base.AbstractBatchInsertImpl;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * LoadData形式
 *
 * @author yky
 * @since 2021/8/5 12:32
 */
@Slf4j
public class LoadDataInsert extends AbstractBatchInsertImpl {
    public LoadDataInsert(int total, int partition) {
        super(total, partition);
    }

    @Override
    public void test() {
        super.batchInsert(lists -> {
            Path path = Paths.get("./", "mysql-loaddata.csv");
            List<String> lines = lists.parallelStream().flatMap(Collection::parallelStream)
                    .map(orders -> String.join(",", orders.getUserId().toString(), orders.getTradeNo(), orders.getTotalFee().toString(), orders.getTradeFee().toString()))
                    .collect(Collectors.toList());
            try {
                Files.write(path, lines);
                Connection connection = getConnection();
                PreparedStatement preparedStatement = connection.prepareStatement("LOAD DATA INFILE ? INTO TABLE week07.orders FIELDS TERMINATED BY ',' (user_id,trade_no,total_fee,trade_fee)");
                preparedStatement.setObject(1, path.toAbsolutePath().toString());
                long start = System.currentTimeMillis();
                preparedStatement.executeUpdate();
                log.info("[批量插入]耗时{}毫秒", System.currentTimeMillis() - start);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }
}
